package cn.newgrand.netcall.smackx.integration;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.provider.IQProvider;
import org.jivesoftware.sparkimpl.updater.SparkVersion;
import org.xmlpull.v1.XmlPullParser;

/**
 * @author SidneyRen E-mail:SidneyRen@hotmail.com
 * @version create time：2010-11-9 下午04:52:33
 * 类说明
 */
public class AppSysIQ extends IQ {
	private Map<String,String> properties = new HashMap<String, String>();  
	
	public void addProperty(String key,String value){
		properties.put(key, value);
	}
	
	public void deleteProperty(String key){
		properties.remove(key);
	}
	
	public void addProperties(Map<String,String> properties){
		this.properties.putAll(properties);
	}
	
	public Map<String,String> getProperties(){
		return properties;
	}
	
	public String getProperty(String key){
		return properties.get(key);
	}
	
	/**
     * Element name of the packet extension.
     */
    public static final String ELEMENT_NAME = "query";
	
	@Override
	public String getChildElementXML() {
		  StringBuilder buf = new StringBuilder();
	        buf.append("<query xmlns=\"jabber:iq:appsys\">");
	        if (properties.size() != 0) {
	        	buf.append("<properties>");
	            for(Entry<String,String> entry:properties.entrySet()){
	            	buf.append("<property>").append("<key>").append(entry.getKey()).append("</key>")
	            	.append("<value>").append(entry.getValue()).append("</value>").append("</property>");
	            }
	            buf.append("</properties>");
	        }
	        buf.append("</query>");
	        return buf.toString();
	}
	/**
     * An IQProvider for SparkVersion packets.
     *
     * @author Derek DeMoro
     */
    public static class Provider implements IQProvider {

        public Provider() {
            super();
        }

        public IQ parseIQ(XmlPullParser parser) throws Exception {
            AppSysIQ version = new AppSysIQ();

            boolean done = false;
            String key = null;
            while (!done) {
                int eventType = parser.next();
                if (eventType == XmlPullParser.START_TAG) {
                    if (parser.getName().equals("key")) {
                        key = parser.nextText();
                    }else if(parser.getName().equals("value")){
                    		version.addProperty(key,parser.nextText());
                    }
                }

                else if (eventType == XmlPullParser.END_TAG) {
                    if (parser.getName().equals(ELEMENT_NAME)) {
                        done = true;
                    }
                }
            }

            return version;
        }
    }
}
	
	
